<?php

/**
 * Presenter pro domeny hromadne aktualizace.
 *
 * @author David Dusek
 */

class DomainPresenter extends \AdminPresenter
{   
    public function renderDefault() {
        if ($this->isAllowed('list', TRUE)) {
            $this->template->title = $this->getTitle("domainTitle", "list");        
        }
    }
    
    public function renderAdd() {
        if ($this->isAllowed('add', TRUE)) {
            $this->template->title = $this->getTitle("domainTitle", "add");
        }
    }
    
    public function renderEdit($id) {        
        $id = $this->getParameter("id");
        $repository = $this->em->getRepository("CMS\Updater\Models\Domain");        
        if ($id === NULL || ($domain = $repository->find($id)) === NULL) {
            $this->flashMessage($this->translate("errDomainIdNotFound"), "error");
            $this->redirect(":Updater:Domain:default");
        }
        
        if ($this->isAllowed('edit', TRUE)) {
            $this->template->title = $this->getTitle("domainTitle", "edit") . " (" . $domain->name . ")";
        }
    }
   
    public function renderChangeKey($id) {        
        $id = $this->getParameter("id");
        $repository = $this->em->getRepository("CMS\Updater\Models\Domain");        
        if ($id === NULL || ($domain = $repository->find($id)) === NULL) {
            $this->flashMessage($this->translate("errDomainIdNotFound"), "error");
            $this->redirect(":Updater:Domain:default");
        }
        
        if ($this->isAllowed('edit', TRUE)) {
            $this->template->title = $this->getTitle("domainTitle", "changeSharedKey");
        }
        $this->template->domain = $domain;
    }
    
    protected function createComponentGrid() {
        $grid = new Gridito\Grid($this, 'grid');
       
        $qb = $this->em->getRepository('\CMS\Updater\Models\Domain')->createQueryBuilder('d')->where("d.deleted = FALSE");
        $grid->setModel(new CMS\DoctrineQueryBuilderModel($qb));
        $grid->addColumn('id', 'Id')->setSortable(true);
        $grid->addColumn('name', $this->translate('name'))->setSortable(true);
        $grid->addColumn('url', $this->translate('url'))->setSortable(true);        
        $grid->addColumn('template.name', $this->translate('template'))->setSortable(true);        
             
        $presenter = $this;
        if ($this->isAllowed("edit")) {
            $grid->addButton('editButton', $this->translate('edit'), array(
                            'icon' => 'ui-icon-pencil',
                            'handler' => function ($domain) use ($presenter) {
                                $presenter->redirect(':Updater:Domain:edit', array("id" => $domain->id));
                            },
                    ))
                    ->setShowText(false);
            
            $grid->addButton('changeKeyButton', $this->translate('changeSharedKey'), array(
                            'icon' => 'ui-icon-key',
                            'handler' => function ($domain) use ($presenter) {
                                $presenter->redirect(':Updater:Domain:changeKey', array("id" => $domain->id));
                            },
                    ))
                    ->setShowText(false);
                            
            $errMsg = $this->translate("revertFail");
            $succMsg = $this->translate("revertSucc");
            $dictionary = $this->dictionary;
            $grid->addButton('revertButton', $this->translate('revert'), array(
                            'icon' => 'ui-icon-seek-prev',
                            'handler' => function ($domain) use ($grid, $dictionary, $succMsg, $errMsg) {
                                $client = new \Updater\JsonRpc\JsonRpcClient($domain->url);
                                $encoded = UpdaterModule::encode(array($domain->sharedKey), $domain->sharedKey);
                                $result = $client->revert($encoded);
                                
                                if ($result["status"]) {
                                    $grid->flashMessage($succMsg);
                                } else {
                                    $grid->flashMessage($errMsg . " (" . $dictionary->translate("updater_" . $result["msg"]) . ")");
                                }                                
                            },
            ))
            ->setConfirmationQuestion($this->translate('revertDomainConfirmQuestion'))
            ->setShowText(false)
            ->setAjax(true);
        }
                
        $em = $this->em;
        $msg = $presenter->translate("msgDomainDeleted");
        if ($this->isAllowed("delete")) {
            $grid->addButton('deleteButton', $this->translate('delete'), array(
                            'icon' => 'ui-icon-trash',
                            'handler' => function ($domain) use ($grid, $presenter, $em, $msg) {
                                $domain->setTemplateNull();
                                $domain->deleted = TRUE;
                                $em->flush();
                                $grid->flashMessage(vsprintf($msg, array($domain->name)));
                            },
                    ))
                    ->setConfirmationQuestion($this->translate('deleteDomainConfirmQuestion'))
                    ->setShowText(false)
                    ->setAjax(true);
        }
    }
    
    protected function createComponentDomainForm() {
        $form = new Nette\Application\UI\Form;
        
        $repository = $this->em->getRepository("\CMS\Updater\Models\Domain");        
        $templates = $this->em->getRepository("\CMS\Updater\Models\Template")->getSelectOptions();
        
        $form->addText("name", $this->translate("name"))->setRequired($this->translate("errRequired"));
        $form->addText("url", $this->translate("url"))->setRequired($this->translate("errRequired"));        
        $form->addSelect("template", $this->translate('template'), $templates);                
        
        if ($this->action == "add") {
            $form->addText("key", $this->translate("sharedKey"))->setRequired($this->translate("errRequired"));
            $form->addSubmit("add", $this->translate("add"));
        } else {
            $form->addSubmit("edit", $this->translate("edit"));
            
            $id = $this->getParameter("id");
            if ($id !== NULL && ($domain = $repository->find($id)) !== NULL) {                
                $values = array();
                $values["name"] = $domain->name;
                $values["url"] = $domain->url;
                $values["template"] = $domain->template->id;
                $form->setDefaults($values);
            }
        }

        $form->onSuccess[] = callback($this, 'domainFormSubmitted');
        return $form;
    }
    
    public function domainFormSubmitted(Nette\Application\UI\Form $form) {
        $values = $form->getValues();
        $action = $this->action;
        $repository = $this->em->getRepository("CMS\Updater\Models\Domain");
        $templateRepository = $this->em->getRepository("CMS\Updater\Models\Template");
        
        if ($action == "add") {
            $domain = new CMS\Updater\Models\Domain;
            $domain->sharedKey = $values["key"];
            $this->flashMessage($this->translate("msgDomainAdded"));
        } else {
            $id = $this->getParameter("id");
            if ($id === NULL || ($domain = $repository->find($id)) === NULL) {
                $form->addError($this->translate("errDomainIdNotFound"));                
            } else {
                $this->flashMessage($this->translate("msgDomainEdited"));
            }
        }
        
        if (!$form->hasErrors()) {
            $domain->name = $values["name"];
            $domain->url = $values["url"];        
            $domain->template = $templateRepository->find($values["template"]);
            $this->em->persist($domain);
            $this->em->flush();
            $this->redirect(":Updater:Domain:edit", array("id" => $domain->id));
        }
    }
    
    protected function createComponentKeyChangeForm() {
        $form = new Nette\Application\UI\Form;
        
        $repository = $this->em->getRepository("CMS\Updater\Models\Domain");
        $id = $this->getParameter("id");
        if ($id !== NULL && ($domain = $repository->find($id)) !== NULL) {
            $form->addText("key", $this->translate("sharedKey"))->setDefaultValue($domain->sharedKey);
            $form->addSubmit("change", $this->translate("change"));
            $form->onSuccess[] = callback($this, 'keyChangeFormSubbmited');
        }
        
        return $form;
    }
    
    public function keyChangeFormSubbmited(Nette\Application\UI\Form $form) {
        $values = $form->getValues();
        
        $id = $this->getParameter("id");
        $repository = $this->em->getRepository("CMS\Updater\Models\Domain");
        if ($id === NULL || ($domain = $repository->find($id)) === NULL) {
            $form->addError($this->translate("errDomainIdNotFound"));
        } else {
            try {                
                $client = new \Updater\JsonRpc\JsonRpcClient($domain->url);                           
                $encoded = UpdaterModule::encode(array($values["key"], $domain->sharedKey), $domain->sharedKey);
                // vzdalene ulozeni sdileneho klice
                $res = $client->changeSharedKey($encoded);
                
                if ($res["status"] === FALSE) {
                    $form->addError($this->translate($res["errMsg"]));
                } else {
                    // lokali ulozeni noveho klice
                    $domain->sharedKey = $values["key"];
                    $this->em->flush();
                    
                    $this->flashMessage($this->translate("changeKeySucc"));
                    $this->redirect(":Updater:Domain:changeKey", array("id" => $domain->id));
                }
            } catch (JsonRpc\JsonRpcException $e){
                $form->addError(vsprintf($this->translate("rpcServerError"), array($e->getMessage())));
            } catch (Updater\JsonRpc\JsonRpcException $e){
                $form->addError(vsprintf($this->translate("rpcServerError"), array($e->getMessage())));
            }
        }
    }
}
